package com.qiyuesuo.client.controller;

import com.qiyuesuo.client.service.FileService;
import com.qiyuesuo.client.util.AES.AESUtils;
import com.qiyuesuo.client.util.RSA.RSASignature;
import com.qiyuesuo.client.util.RSA.RSAUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.UUID;

/**
 * @author s77
 * @create 2020-4月-02 16:16
 */
@Controller
public class DownloadController {
    private final static Logger logger = LoggerFactory.getLogger(DownloadController.class);

    private static final String REQUEST_PATH = "http://localhost:8081/download?fileName=";
    private static final String METHOD = "GET";

    @Autowired
    @Qualifier("fileService")
    private FileService fileService;

    @ResponseBody
    @RequestMapping("download")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName) throws Exception {
        //读取RSA私钥
        String privateKey = "";
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("privateKey.txt");
        try (Scanner scanner = new Scanner(is)) {
            while (scanner.hasNextLine()) {
                privateKey += scanner.nextLine();
            }
        } catch (Exception e) {
            logger.error("读取私钥文件失败", e);
        }
        HttpURLConnection httpConn = fileService.gethttpConn(REQUEST_PATH + fileName, METHOD);
        response.setHeader("Content-Disposition", httpConn.getHeaderField("Content-Disposition"));
        response.setHeader("Content-Type", "application/octet-stream");
        response.setCharacterEncoding("GBK");
        //获取数字信封并用私钥解密，获得ASE的对称密钥
        String digitalEnvelope = httpConn.getHeaderField("digitalEnvelope");
        String secretKey = RSAUtil.decrypt(digitalEnvelope, privateKey);
        //输入输出流
        ServletOutputStream outputStream = response.getOutputStream();
        InputStream inputStream = httpConn.getInputStream();
        AESUtils.decryptStream(secretKey, inputStream, outputStream);
        inputStream.close();
        outputStream.close();
        httpConn.disconnect();

    }

}
